# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: util_pdf.py
@time: 2025/3/28 15:22 
@desc: 

"""
import os
import PyPDF2
from pdf2image import convert_from_path
from uuid import uuid4


class pdfCheck:
    """

    """

    def __init__(self, file, tmp_file="./tmp"):
        self.file = file
        self.reader = None
        self.file_obj = None
        self.pages = 0
        self.tmp_file = tmp_file
        os.makedirs(self.tmp_file, exist_ok=True)
        self.first_name = f"{self.tmp_file}/{uuid4()}.png"
        print("首页图片:", self.first_name)

    def __enter__(self):
        self.file_obj = open(self.file, 'rb')
        self.reader = PyPDF2.PdfReader(self.file_obj)
        self.num_pages = len(self.reader.pages)
        print("pdf 页数:", self.num_pages)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file_obj:
            self.file_obj.close()

    def save_first_page(self):
        """

        :return:
        """
        images = convert_from_path(self.file, first_page=1, last_page=1, poppler_path=r"./poppler/Library/bin")
        if images:
            # 保存第一页的图像
            images[0].save(self.first_name, 'PNG')
            print(f"{self.file} 首页图片已保存至 {self.first_name}")
            return self.first_name
        else:
            print(f"无法提取{self.file}首页图片。")
            return None


if __name__ == '__main__':
    with pdfCheck(
            r"D:\Desktop\6\tmp_巨潮网_2025-03-28-15-21-17\pdf\新创建集团有限公司\年报\新创建集团有限公司2024年年报.pdf") as pdf:
        pdf.save_first_page()
        print(pdf.num_pages)
